<!--
 * @Author: your name
 * @Date: 2022-04-09 14:22:23
 * @LastEditTime: 2022-04-15 14:11:08
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \nien-vue3-admin\src\views\system\dict\index.vue
-->
<template>
  <div class="app-container">
    <custom-container ref="customContainerRef" :config="mainConfig" />
    <!-- 添加或修改参数配置对话框 -->
    <setForm
      ref="setFormRef"
      v-model:open="open"
      :title="title"
      :data-type-disabled="dataTypeDisabled"
      @change-list="handleQuery"
    />
  </div>
</template>

<script lang="ts" setup>
import { Delete, Refresh, Plus, Edit } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, defineAsyncComponent, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElButton } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { listType, delType, clearCache, getData } from '@/api/system/dict'
import { DictDirection } from '@/store/modules/dicts'

const setForm = defineAsyncComponent(() => import('./components/setForm.vue'))
const routers = useRouter()
const { t } = useI18n()
// 选中数组
let ids = [],
  // 新增修改的按钮
  open = ref(false),
  title = ref(undefined),
  dataTypeDisabled = ref(false),
  dictTypes = []
const 
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  // 查询参数
  queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    dictName: undefined,
    dictType: undefined,
    status: undefined,
  }),
  customContainerRef = ref(null),
  setFormRef = ref(null),
  {
    proxy,
  }:{
    proxy,
  } = getCurrentInstance()
// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
// 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  ids = rows.map((item) => item.dictId)
  dictTypes = rows.map((item) => item.dictType)
  single.value = rows.length != 1
  multiple.value = !rows.length
}

// 修改
const handleUpdate = (row: { [key: string]: any }) => {
  const dictId = row?.dictId || ids[0]
  open.value = true
  title.value = '修改字典类型'
  setFormRef.value.getList(dictId)
  const dictTypeList = row.dictType || dictTypes[0]
  const data = { dictType: dictTypeList, pageNum: 1, pageSize: 10 }
  getData(data).then(res => {
    if (res.total === 0) {
      dataTypeDisabled.value = false
    } else {
      dataTypeDisabled.value = true
    }
  })
}
// 删除
const handleDelete = (row: { [key: string]: any }) => {
  let dictIds = row.dictId || ids
  if (!Array.isArray(dictIds)) {
    dictIds = [dictIds]
  }
  ElMessageBox.confirm(`是否确认删除字典编号为"${ dictIds }"的数据项?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(() => delType(dictIds))
  .then((res) => {
    if (res.code === 200) {
      handleQuery()
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch(() => {})
}
// 新增
const handleAdd = () => {
  open.value = true
  title.value = '新增字典类型'
}
// 详情
const handleRouterPush = (row: { [key: string]: any }) => {
  routers.push(`/dict/type/data/${ row.dictId }`)
}
// 清理缓存
const handleClearCache = () => {
  clearCache()
  .then((res) => {
    if (res.code === 200) {
      ElMessage.success('清理成功')
    } else {
      ElMessage.error(res.msg)
    }
  })
  .catch((error) => {
    ElMessage.error(error)
  })
}

// 主体配置
const mainConfig = computed(() => {
  const queryField = 'system.dict.queryField.'
  const btns = 'system.dict.btns.'
  const columns = 'system.dict.columns.'
  const publicKey = 'public.'
  return {
    query: {
      fields: [
        {
          label: t(`${ queryField }dictName`),
          prop: 'dictName',
        },
        {
          label: t(`${ queryField }dictType`),
          prop: 'dictType',
        },
        {
          label: proxy.$t(`${ queryField }status`),
          prop: 'status',
          type: 'select',
          option: {
            dictInfo: { dict: DictDirection.是否禁用字典 },
          },
        },
        {
          label: proxy.$t(`${ queryField }createTime`),
          type: 'datePicker',
          prop: 'dateRange',
          option: {
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
          },
        },
      ],
      queryParams: queryParams.value,
      formOption: {
        labelWidth: '0.65rem',
      },
    },
    btns: [
      {
        title: t(`${ publicKey }add`),                       
        icon: Plus,
        directive: [['hasPermi', ['system:dict:add']]],
        onClick: handleAdd,
      },
      {
        title: t(`${ publicKey }edit`),                       
        icon: Edit,
        type: 'warning',
        disabled: single.value,
        directive: [['hasPermi', ['system:dict:edit']]],
        onClick: handleUpdate,
      },
      {
        title: t(`${ publicKey }del`),
        icon: Delete,
        type: 'danger',
        disabled: multiple.value,
        directive: [['hasPermi', ['system:dict:remove']]],
        onClick: handleDelete,
      },
      {
        title: t(`${ btns }clearLocal`),
        icon: Refresh,
        type: 'danger',
        directive: [['hasPermi', ['system:dict:remove']]],
        onClick: handleClearCache,
      },
    ],
    table: {
      columns: [
        { type: 'selection', width: '55', align: 'center' },
        {
          label: t(`${ columns }dictionaryNumber`),
          prop: 'dictId',
          align: 'center',
          width: '90',
        },
        {
          label: t(`${ columns }dictionaryName`),
          prop: 'dictName',
          align: 'center',
        },
        {
          label: t(`${ columns }dictionaryType`),
          prop: 'dictType',
          align: 'center',
        },
        {
          label: t(`${ columns }status`),
          prop: 'status',
          align: 'center',
          autoFormatter: {
            dict: DictDirection.是否禁用字典,
            rowKey: 'status',
          },
        },
        {
          label: t(`${ columns }remark`),
          prop: 'remark',
          align: 'center',
        },
        {
          label: t(`${ columns }createTime`),
          prop: 'createTime',
          align: 'center',
        },
        {
          label: t(`${ columns }operation`),
          align: 'center',
          prop: 'opera',
          showOverflowTooltip: false,
          className: 'custormFixedCol',
          fixed: 'right',
          render: (h, params) => {
            const buttons = [
              {
                title: t(`${ publicKey }edit`),
                // icon: Edit,
                clickFun: handleUpdate,
              },
              {
                title: t(`${ publicKey }del`),
                // icon: Delete,
                clickFun: handleDelete,
              },
              {
                title: t(`${ publicKey }detail`),
                // icon: Document,
                clickFun: handleRouterPush,
              },
            ]
            return buttons.map((el) => h(
              ElButton,
              {
                text: true,
                type: 'primary',
                // icon: el.icon,
                onClick: () => {
                  el.clickFun(params.row)
                },
              },
              {
                default: () => el.title,
              },
            ))
          },
        },
      ],
      event: {
        onSelectionChange: (rows) => {
          handleSelectionChange(rows)
        },
      },
    },
    api: listType,
    customKey: 'system/dict',
  }
})

</script>
